﻿using SpaceNeedle.City6473.Web.Data.Models;
using SpaceNeedle.City6473.Web.Data.Repositories;
using SpaceNeedle.City6473.WebSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SpaceNeedle.City6473.WebSite.Security.Mvc;


namespace SpaceNeedle.City6473.WebSite.Controllers
{
    public class AppsController : GlobalController
    {
        public List<SelectListItem> DropDownList()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Controle Total", Value = "0", Selected = true });
            list.Add(new SelectListItem { Text = "Criação de Solicitações e Alertas", Value = "1"});
            list.Add(new SelectListItem { Text = "Criação de Alertas", Value = "2"});
            list.Add(new SelectListItem { Text = "Somente Leitura", Value = "3"});

            return list;
        }

        // GET: Apps
        [Secure]
        public ActionResult Index()
        {
            AppRepository appRepository = new AppRepository();

            var model = new AppsModel();
            model.Apps = appRepository.GetAll().OrderByDescending(x => x.Id).ToList();

            return View(model);
        }

        [Secure]
        public ActionResult Create()
        {
            ViewBag.PermissionLevel = DropDownList();
            return View();
        }

        [Secure]
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            var name = collection["name"];
            var icon = collection["icon"];
            var uri = collection["uri"];
            var isEnabled = Convert.ToBoolean(collection["isEnabled"]);
            var permissionLevel = Convert.ToInt32(collection["permissionLevel"]);
            var description = collection["description"];

            AppRepository appRepository = new AppRepository();

            App app = new App();

            app.Id = Guid.NewGuid();
            app.Name = name;
            app.Icon = icon;
            app.Uri = uri;
            app.IsEnabled = isEnabled;
            app.PermissionLevel = permissionLevel;
            app.Description = description;
            app.AppSecret = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
            app.CreatedBy = Auth.CurrentUser.Id;

            appRepository.Insert(app);

            return RedirectToAction("Index", "Apps");
        }
    }
}
